package cc.shacocloud.mirage.utils.converter.support;

import cc.shacocloud.mirage.utils.converter.ConversionException;
import cc.shacocloud.mirage.utils.converter.ConversionSupport;
import cc.shacocloud.mirage.utils.converter.TypeDescriptor;
import org.jetbrains.annotations.NotNull;

import java.util.Locale;

/**
 * 转换为 {@link Locale} 类型的转换器
 *
 * @author 思追(shaco)
 */
public class ToLocaleConversion extends AbstractConversion implements ConversionSupport {
    
    @Override
    public boolean support(@NotNull TypeDescriptor sourceType, @NotNull TypeDescriptor targetType) {
        Class<?> objectType = targetType.getObjectType();
        return Locale.class.equals(objectType);
    }
    
    @Override
    public Object convert(@NotNull Object source, @NotNull TypeDescriptor sourceType, @NotNull TypeDescriptor targetType) throws ConversionException {
        if (source instanceof Locale) {
            return source;
        }
        
        try {
            String str = convertToStr(source);
            
            final String[] items = str.split("_");
            if (items.length == 1) {
                return new Locale(items[0]);
            }
            if (items.length == 2) {
                return new Locale(items[0], items[1]);
            }
            return new Locale(items[0], items[1], items[2]);
        } catch (Exception e) {
            throw new ConversionException(sourceType, targetType, source, e);
        }
        
    }
}
